#!/bin/sh

# the following is chkconfig init header
#
# zstack-sftpbackupstorage:  zstack sftp-backup-storage agent daemon
#
# chkconfig: 345 97 03
# description:  This is a daemon instructed by zstack management server \
#               to perform backup storage related operations\
#               See http://zstack.org
#
# processname: sftpbackupstorage
# pidfile: /var/run/zstack/sftpbackupstorageagent.pid
#

check_status() {
	pidfile='/var/run/zstack/sftpbackupstorageagent.pid'
	if [ ! -f $pidfile ]; then
		echo "zstack sftp-backup-storage agent is stopped"
		exit 1
	else
		pid=`cat $pidfile`
		ps -p $pid > /dev/null
		if [ $? -eq 0 ]; then
			echo "zstack sftp-backup-storage agent is running, pid is $pid"
			exit 0
		else
			echo "zstack sftp-backup-storage is stopped, but pidfile at $pidfile is not cleaned. It may be caused by the agent crashed at last time, manually cleaning it would be ok"
			exit 1
		fi
	fi
}

if [ $# -eq 0 ]; then
	echo "usage: $0
[start|stop|restart|status]"
	exit 1
fi

if [ "$@" = "status" ]; then
	check_status
else
	. /var/lib/zstack/virtualenv/sftpbackupstorage/bin/activate && python -c "from sftpbackupstorage import sftpbackupstoragedaemon; sftpbackupstoragedaemon.main()" $@
fi

if [ $? -eq 0 ]; then
    echo "$@ zstack sftp-backup-storage agent .... SUCCESS"
    exit 0
else
    echo "$@ zstack sftp-backup-storage agent .... FAILED"
    exit 1
fi
